// const gloabl = getApp().globalData;
const ENV = require('../config/env.conf');
const httpEnum = {
  "dev": 'https://inapi.jydsapp.com',
  "prod": 'https://pa.jydsapp.com',
  "local": "http://localtest.jydsapp.com:8182"
}
const BASE_URL = httpEnum[ENV];

const http = {
  baseurl: BASE_URL,
  __header: {},
  addHeader(params) {
    this.__header = Object.assign(this.__header, params);
  },
  header(params) {
    this.__header = params;
    return this;
  },
  get(url, data, callback) {
    this.request('GET', url, data, callback);
  },
  post(url, data, callback) {
    this.request('POST', url, data, callback);
  },
  put(url, data, callback) {
    this.request('PUT', url, data, callback);
  },
  delete(url, data, callback) {
    this.request('DELETE', url, data, callback);
  },
  request(method, url, data, callback) {
    wx.showNavigationBarLoading();
    let cookie = wx.getStorageSync('cookieKey');
    let header = {
      'os-version': getApp().globalData.version,
      'content-type': 'application/json',
      'sys-type': '3', //客户端类型 1app，2公众号，3小程序
      ...this.__header
    }
    if (cookie) {
      header.Cookie = cookie;
    }
    let params = {
      url: this.baseurl + url,
      method: method,
      header: header,
      success: function(res) {
        if(res && res.header && res.header['Set-Cookie']){
          wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
        }
        wx.hideNavigationBarLoading();
        let data = res.data;
        callback(data.data, data.code);
        if (data.code !== 0) {

          if (data.code === 9) {
            wx.showToast({
              title: '您的账号已在其他设备登录',
              icon: 'none',
              duration: 2000
            })
            return;
          } 
          wx.showToast({
            title: data.message,
            icon: 'none',
            duration: 2000
          })
          return;
        }
        // callback(data.data, data.code);
      },
      fail: function(err) {
        if (err.errMsg.indexOf('request:fail') > -1) {
          wx.showToast({
            title: '网络异常！',
            icon: 'none'
          });
        }
        wx.hideNavigationBarLoading();

        throw err;
      }
    }
    data && (params.data = data);
    wx.request(params);
  }
}

function getAccessToken() {

}
module.exports = http;